import React, { Component } from 'react'
import { addPerson } from '../redux/person_action'
import { connect } from "react-redux"
import { nanoid } from "nanoid"

// 定义UI组件
class Person extends Component {
  add = () => {
    const name = this.nameNode.value
    const age = this.ageNode.value
    this.props.addPerson({ id: nanoid(), name, age })
  }
  render() {
    const { person } = this.props
    const { count } = this.props
    return (
      <div>
        <h2>计数器计数{count}</h2>
        name: <input ref={nameNode => this.nameNode = nameNode} type="text" />
        age: <input ref={ageNode => this.ageNode = ageNode} type="text" />
        <button onClick={this.add}>添加</button>

        <ul>
          {
            person.map(p => {
              return (
                <div key={p.id}>
                  <li>name:{p.name}</li>
                  <li>age:{p.age}</li>
                  <hr />
                </div>
              )
            })
          }
        </ul>
      </div>
    )
  }
}

// 将 state映射到 ui组件中props属性
const mapStateToProps = (state) => {
  return {
    person: state.person,
    count: state.count
  }
}

// 将 dispatch映射到 ui组件中props属性
const mapDispatchToProps = (dispatch) => ({
  addPerson: data => dispatch(addPerson(data))
})

export default connect(mapStateToProps, mapDispatchToProps)(Person)